package cn.kgc.web;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@WebServlet(urlPatterns = "/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //请求信息中的内容是否是multipart类型
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        try {
            if(isMultipart){
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List<FileItem> items = upload.parseRequest(request);
                Iterator<FileItem> iter = items.iterator();
                while (iter.hasNext()){
                    FileItem item = iter.next();
                    if(item.isFormField()){
                        //普通表单字段
                        String fieldName = item.getFieldName();
                        if("name".equals(fieldName)){
                            String name = item.getString("utf-8");
                            System.out.println(name);
                        }
                    }else{
                        //文件表单字段
                        //上传文件的存储路径（服务器文件系统上的绝对）
                        String uploadPath = request.getServletContext().getRealPath("/imgs");
                        File f = new File(uploadPath);
                        if(!f.exists()){
                            f.mkdir();
                        }
                        String fname = item.getName();
                        fname = System.currentTimeMillis()+fname;
                        File ufile = new File(uploadPath,fname);
                        item.write(ufile);
                        System.out.println(uploadPath);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
